package com.hertz.alarm.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.hertz.alarm.dao.EhCacheDao;
import com.hertz.alarm.entity.IrisNbaAlarm;
import com.hertz.alarm.entity.MatchNba;
import com.hertz.alarm.service.EntityService;
import com.hertz.alarm.service.MatchNbaService;
import com.hertz.alarm.util.CollectionUtil;
import com.hertz.alarm.util.Constants4Ehcache;
@Service
public class MatchNbaServiceImpl extends BaseServiceImpl implements MatchNbaService {
	private Logger logger = LoggerFactory.getLogger(MatchNbaServiceImpl.class);
	@Resource
	private EntityService entityService;
	@Resource
	private EhCacheDao ehcacheDao;
//	@Resource
//	private EhCacheDao ehcacheDao;
	@Override
	public MatchNba getBySourceId(String sourceId) {
		String key = String.format(Constants4Ehcache.KEY_MATCH_SOURCEID, sourceId);
		Object obj = ehcacheDao.get(key, Constants4Ehcache.REGION_MATCH);
		if(obj == null){
			MatchNba mn = baseDAO.getUniqueResult(MatchNba.GET_BY_SOURCE_ID, sourceId);
			ehcacheDao.save(key, mn, Constants4Ehcache.REGION_MATCH);
			save2cache(mn);
			return mn;
		}else{
			return (MatchNba)obj;
		}
	}

	@Override
	public List<MatchNba> listByYmd(String ymd) {
		String keyIds = String.format(Constants4Ehcache.KEY_MATCH_ID_YMD, ymd);
		Object obj = ehcacheDao.get(keyIds, Constants4Ehcache.REGION_MATCH);
		List<Long> mids = (ArrayList<Long>)obj;
		if(obj == null){
			mids = new ArrayList<Long>();
			List<MatchNba> list = baseDAO.listAll(MatchNba.GETS_BY_YMD,ymd);
			if(list != null){
				for(int i = 0; i < list.size(); i++){
					MatchNba mn = list.get(i);
					mids.add(mn.getId());
				}
			}
			ehcacheDao.save(keyIds, mids, Constants4Ehcache.REGION_MATCH);
		}
		List<MatchNba> result = new ArrayList<MatchNba>();
		for(Long id : mids){
			result.add(getById(id));
		}
		return result;
	}

	@Override
	public MatchNba getById(Long id) {
		String key = String.format(Constants4Ehcache.KEY_MATCH, id.toString());
		Object obj = ehcacheDao.get(key, Constants4Ehcache.REGION_MATCH);
		if(obj == null){
			MatchNba mn = entityService.getById(id, MatchNba.class);
			save2cache(mn);
			return mn;
		}else{
			return (MatchNba)obj;
		}
	}
	
	public void update(MatchNba matchNba){
		entityService.update(matchNba);
		save2cache(matchNba);
	}
	
	private void save2cache(MatchNba matchNba){
		String sourceKey = String.format(Constants4Ehcache.KEY_MATCH_SOURCEID, matchNba.getSourceId());
		String key = String.format(Constants4Ehcache.KEY_MATCH, matchNba.getId().toString());
		ehcacheDao.save(sourceKey, matchNba, Constants4Ehcache.REGION_MATCH);
		ehcacheDao.save(key, matchNba, Constants4Ehcache.REGION_MATCH);
	}
}
